/**
 * 
 */
package bi.uc.client;

import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import com.bi_uc.www.R;

import bi.uc.login.Info;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;

public class NewMemberActivity extends Activity implements Runnable{

	Spinner spinCardType;
	String cardLevelString;
	String cardTypeSring;
	Spinner spinCardLevel;
	EditText cardNum;
	String cardNumString;
	EditText cardPassword;
	String cardPasswordString;
	EditText confirmPassword;
	String confirmPasswordString;
	EditText cardUser;
	String cardUserString;
	Spinner spinSex;
	String sexString;
	EditText txTel;
	String txTelString;
	CheckBox isPrint;
	Info info = Info.getInfo();
	private ArrayAdapter<String> CardTypeAd = null;
	private ArrayAdapter<String> CardLevelAd = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		((ExitApplication)getApplication()).addActivity(this);
		setContentView(R.layout.newmember);
		initWidget();
	}

	private void initWidget() {
		// TODO Auto-generated method stub
		spinCardType = (Spinner) findViewById(R.id.spinCardType);
		spinCardLevel = (Spinner) findViewById(R.id.spinCardLevel);
		cardNum = (EditText) findViewById(R.id.cardNum);
		cardPassword = (EditText) findViewById(R.id.cardPassword);
		confirmPassword = (EditText) findViewById(R.id.confirmPassword);
		cardUser = (EditText) findViewById(R.id.cardUser);
		spinSex = (Spinner) findViewById(R.id.spinSex);
		txTel = (EditText) findViewById(R.id.txTel);
		isPrint = (CheckBox) findViewById(R.id.isPrint);
		CardTypeAd = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, info.cardTypes);
		CardTypeAd
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinCardType.setAdapter(CardTypeAd);
		spinCardType.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> ad, View v, int index,
					long id) {
				// TODO Auto-generated method stub
				cardTypeSring = ad.getItemAtPosition(index).toString();
				CardLevelAd = new ArrayAdapter<String>(NewMemberActivity.this,
						android.R.layout.simple_spinner_item, info.cardLeves
								.get(ad.getItemAtPosition(index).toString()));
				CardLevelAd
						.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				spinCardLevel.setAdapter(CardLevelAd);

			}

			@Override
			public void onNothingSelected(AdapterView<?> ad) {
				// TODO Auto-generated method stub
			}
		});

		spinCardLevel.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> ad, View v, int index,
					long id) {
				// TODO Auto-generated method stub
				cardLevelString = ad.getItemAtPosition(index).toString();
			}

			@Override
			public void onNothingSelected(AdapterView<?> ad) {
				// TODO Auto-generated method stub

			}
		});

		spinSex.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> ad, View v, int index,
					long id) {
				// TODO Auto-generated method stub
//				sexString = ad.getItemAtPosition(index).toString();
				sexString = String.valueOf(index);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});
	}

	public void btnClick(View view) {
		if (info.stopFlag) {
			Toast.makeText(this, "网络未连接，请确保您的网络已连接！", Toast.LENGTH_SHORT)
					.show();
			return;
		}
		
		cardNumString = cardNum.getText().toString();
		cardPasswordString = cardPassword.getText().toString();
		confirmPasswordString = confirmPassword.getText().toString();
		cardUserString = cardUser.getText().toString();
		txTelString = txTel.getText().toString();
		if ("".equals(cardNumString)) {
			Toast.makeText(this, "请输入卡号！", Toast.LENGTH_SHORT).show();
			return;
		}

		if ("".equals(cardPasswordString)) {
			Toast.makeText(this, "请输入密码！", Toast.LENGTH_SHORT).show();
			return;
		}else if (cardPasswordString.length()<6) {
			Toast.makeText(this, "输入密码长度小于6位，请重新输入！", Toast.LENGTH_SHORT).show();
			return;
		}

		if ("".equals(confirmPasswordString)) {
			Toast.makeText(this, "请输入重复密码！", Toast.LENGTH_SHORT).show();
			return;
		} else if (!confirmPasswordString.equals(cardPasswordString)) {
			Toast.makeText(this, "两次密码输入不一致，请重新输入！", Toast.LENGTH_SHORT).show();
			return;
		}

		if ("".equals(cardUserString)) {
			Toast.makeText(this, "请输入会员姓名！", Toast.LENGTH_SHORT).show();
			return;
		}

		if ("".equals(txTelString)) {
			Toast.makeText(this, "请输入手机号码！", Toast.LENGTH_SHORT).show();
			return;
		}else if (!isMobileNO(txTelString)) {
			Toast.makeText(this, "手机号码输入格式不正确！", Toast.LENGTH_SHORT).show();
			return;
		}
			
			Log.d("data", "cardNumString = "+cardNumString+", confirmPasswordString = "+confirmPasswordString+
					", confirmPasswordString = "+confirmPasswordString+", cardUserString = "+cardUserString+", txTelString = "
					+txTelString);
			new Thread(this).start();
			
			
		
	}

	private void sendNewMemberInfo() throws Exception {
		String Url = "http://bi.bi-uc.com/BI.api";
		String Body = "Action=PDA-新增会员&商家=" + info.employID + "&店面="
				+ info.shopID + "&操作员=" + info.userID + "&卡类别="
				+ info.NameId.get(cardTypeSring) + "&卡级别="
				+ info.NameId.get(cardLevelString) + "&卡号=" + cardNumString
				+ "&密码=" + cardPasswordString + "&姓名=" + cardUserString
				+ "&称谓=" + sexString + "&手机=" + txTelString;
//		String Body = "Action=PDA-新增会员&商家=529&店面=943&操作员=331&卡类别=" +
//				"972&卡级别=397&卡号=1234567&密码=123456&姓名=WWL&称谓=1&手机=13312345678";
		byte[] bs = Body.getBytes("UTF-8");
		URL u = new URL(Url);
		HttpURLConnection con = (HttpURLConnection) u.openConnection();
		con.setRequestMethod("POST");
		con.setConnectTimeout(6*1000);
		con.setDoOutput(true);
		con.setDoInput(true);
		con.setUseCaches(false);
		con.setRequestProperty("Content-length", "" + bs.length);
		// httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
		con.setRequestProperty("Charset", "UTF-8");
		con.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		// httpConn.setRequestProperty("Content-Type",
		// "application/octet-stream");
		OutputStream write = con.getOutputStream();
		write.write(bs);
		write.flush();
		write.close();

/*		StringBuffer sb = new StringBuffer();
		// 当正确响应时处理数据
		String readLine;
		// 处理响应流，必须与服务器响应流输出的编码一致
		BufferedReader responseReader = new BufferedReader(
				new InputStreamReader(con.getInputStream(), "UTF-8"));

		// parser.setInput(new InputStreamReader(con.getInputStream(),
		// "UTF-8"));

		while ((readLine = responseReader.readLine()) != null) {
			sb.append(readLine).append("\n");
		}
		responseReader.close();
		Log.d("data", "结果1" + sb);
*/

		int responseCode = con.getResponseCode();
		if (HttpURLConnection.HTTP_OK == responseCode) {// 连接成功 //
		// 由android.util.Xml创建一个XmlPullParser实例
			XmlPullParserFactory pullParserFactory = XmlPullParserFactory
					.newInstance(); //
			// 获取XmlPullParser的实例
			final XmlPullParser parser = pullParserFactory.newPullParser();
			InputStreamReader responseReader = new InputStreamReader(
					con.getInputStream(), "UTF-8");
			parser.setInput(responseReader);
			parser.next();
			int eventType = parser.getEventType();
			if (eventType != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_TAG
						&& parser.getName().equals("XML")) { // String result =
					parser.getAttributeValue(0);
					String result = parser.getAttributeValue(null, "EXEC");
					if (result.equals("True")) {
						info.card.cardNum = cardNumString;
						info.updata();
						Intent intent = getIntent();						 
						/* 将数据打包到aintent Bundle 的过程略 */
						this.setResult(RESULT_OK, intent); //这理有2个参数(int resultCode, Intent intent)															 
						finish();
						Log.d("data", "新建会员成功！");
					} else {
						
						final String error = parser.getAttributeValue(null, "错误消息");
						Log.e("data",error);
						if (error.contains("您的可用短信数量为")) {
							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									// TODO Auto-generated method stub
									Toast.makeText(NewMemberActivity.this, error,
											Toast.LENGTH_SHORT).show();
									Intent intent = getIntent();						 
									/* 将数据打包到aintent Bundle 的过程略 */
									setResult(RESULT_OK, intent); //这理有2个参数(int resultCode, Intent intent)															 
									finish();
								}
								
							});
							
						} else {
							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									// TODO Auto-generated method stub
									Toast.makeText(NewMemberActivity.this, "新建会员失败！"+error,
											Toast.LENGTH_SHORT).show();
								}
							});
						}
						
					}
				}
			}
			responseReader.close();
			con.disconnect();
		} else {
			con.disconnect();
			runOnUiThread(new Runnable() {				
				@Override
				public void run() {
					Toast.makeText(NewMemberActivity.this, "连接超时，请确保网络连接正常！", Toast.LENGTH_SHORT).show();
					}
			});							
		}
		 
	}

	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			sendNewMemberInfo();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onTouchEvent(android.view.MotionEvent)
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		InputMethodManager imm= (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		 if  (event.getAction() == MotionEvent.ACTION_DOWN) {  

            System.out.println("down" );  

            if  (this .getCurrentFocus() !=  null ) {  

                if  (this .getCurrentFocus().getWindowToken() !=  null ) {  

                    imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),  

                            0);  

                }  

            }  

        }  
		return super.onTouchEvent(event);
	}
	
	public boolean isMobileNO(String mobiles) {

        Pattern p = Pattern.compile("^1[3|4|5|8]\\d{9}(,1[3|4|5|8]\\d{9})*$");
        Matcher m = p.matcher(mobiles);
        System.out.println(m.matches() + "---");
        return m.matches();
    }
}
